/**
* AutoSWF - Cody Cushing. March 26, 2009
* Copyright (c) 2009 Cody Cushing
* No use restrictions. Maintain this notice in all versions. 
**/

package com.autoswf.lattice
{
	import flash.events.Event;
	
	import flexunit.framework.TestCase;

	public class AsyncLatticeTest extends TestCase
	{
		public function AsyncLatticeTest(methodName:String=null)
		{
			super(methodName);
		}
		
		private var lattice:AsyncLattice = new AsyncLattice();
		private var mockLattice1:Lattice = new Lattice();
		private var mockLattice2:Lattice = new Lattice();
		
		private var closureWasInvoked:Boolean;
		private var closure:Function = function():void
		{
			closureWasInvoked = true;
		}
		
		private var asyncCommand:AsyncCommand = new AsyncCommand();
		
		
		
		/** Lattice invokes a command and waits for Event.COMPLETE before starting the next node(s). */
		public function testAsyncComplete01():void
		{
			lattice.addNext(mockLattice1);
			lattice.watch(asyncCommand).completeTriggers(Event.COMPLETE);
			lattice.onExecute(asyncCommand).execute();
			
			assertTrue(asyncCommand.wasInvoked);
			assertFalse(mockLattice1.hasCompleted);
			
			asyncCommand.dispatchEvent(new Event(Event.COMPLETE));
			
			assertTrue(mockLattice1.hasCompleted);
		}
		
		
		/** Lattice invokes onComplete closure after the completion event. */
		public function testAsyncComplete02():void
		{
			lattice.addNext(mockLattice1);
			lattice.watch(asyncCommand).completeTriggers(Event.COMPLETE);
			lattice.onComplete(closure);
			lattice.onExecute(asyncCommand).execute();
			
			assertFalse(closureWasInvoked);
			
			asyncCommand.dispatchEvent(new Event(Event.COMPLETE));
			
			assertTrue(closureWasInvoked);
		}
		
		
		/** Lattice invokes a command, calls onCancel if execution is cancelled, starts next lattice nodes. */
		public function testAsyncCancel01():void
		{
			lattice.addNext(mockLattice1);
			lattice.watch(asyncCommand).cancelTriggers(Event.CANCEL);
			lattice.onExecute(asyncCommand).execute();
			
			asyncCommand.dispatchEvent(new Event(Event.CANCEL));
			
			assertTrue(mockLattice1.hasCompleted);
		}
		
		/** Lattice invokes onCancel closure after a fail like event. */
		public function testAsyncCancel02():void
		{
			lattice.addNext(mockLattice1);
			lattice.watch(asyncCommand).cancelTriggers(Event.CANCEL);
			lattice.onCancel(closure);
			lattice.onExecute(asyncCommand).execute();
			
			asyncCommand.dispatchEvent(new Event(Event.CANCEL));
			
			assertTrue(closureWasInvoked);
		}
		
	}
}


import flash.events.EventDispatcher;
import flash.events.Event;

internal class AsyncCommand extends EventDispatcher
{
	public var wasInvoked:Boolean;
	
	public function AsyncCommand()
	{}
	
	public function execute():void
	{
		wasInvoked = true;
	}
}